package socket

import (
	"fmt"
	"sync"
)

type Message struct {
	From    string `json:"from"`
	To      string `json:"to"`
	Message string `json:"message"`
	Type    uint32 `json:"Type"`
}
type Broadcast struct {
	From    string `json:"from"`
	Message string `json:"message"`
	Type    uint8  `json:"type"`
}
type SocketManager struct {
	Clients    map[*Client]bool   // 所有客户端链接
	Users      map[string]*Client // 所有用户和对应的链接
	Register   chan *Client       // 注册链接
	UnRegister chan *Client       // 注销链接
	ClientLock sync.RWMutex       // 客户端注册断开的锁
	UserLock   sync.RWMutex       // 用户发送消息读写锁
	Message    chan *Message      // 消息通道
	Broadcast  chan *Broadcast    //广播所有消息
	//Ping chan
}
type ISocketManager interface {
	Start()
	Stop()
}

func NewSocketManager() *SocketManager {
	return &SocketManager{
		Clients:    make(map[*Client]bool),
		Users:      make(map[string]*Client),
		Register:   make(chan *Client, 1000),
		UnRegister: make(chan *Client, 1000),
		ClientLock: sync.RWMutex{},
		UserLock:   sync.RWMutex{},
		Message:    make(chan *Message),
		Broadcast:  make(chan *Broadcast),
	}
}
func (sm *SocketManager) Start() {
	for {
		select {
		case message := <-sm.Register:
			sm.Login(message)
		case message := <-sm.UnRegister:
			fmt.Println(message)
		case message := <-sm.Message:
			sm.Send(message)
		case message := <-sm.Broadcast:
			fmt.Println("broadcast", message)
		}
	}
}
func (sm *SocketManager) Login(client *Client) {
	sm.ClientLock.Lock()
	defer sm.ClientLock.Unlock()
	if !sm.Clients[client] && sm.Users[client.ID] == nil {
		sm.Clients[client] = true
		sm.Users[client.ID] = client
	}
}
func (sm *SocketManager) Send(message *Message) {
	sm.UserLock.Lock()
	defer sm.UserLock.Unlock()
	for userId, client := range sm.Users {
		if userId == message.To {
			client.SendMsg(message)
		}
	}

}
